package pers.w.chaptertalk.ui.me;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.widget.Toast;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import pers.w.chaptertalk.R;
import pers.w.chaptertalk.funs.BookInfo;
import pers.w.chaptertalk.funs.ChapterThread;
import pers.w.chaptertalk.funs.Fun;
import pers.w.chaptertalk.funs.IReader;
import pers.w.chaptertalk.funs.db.Tab_Book;
import pers.w.chaptertalk.funs.db.Tab_BookProgress;

public class MeViewModel extends ViewModel implements IReader {

    private MutableLiveData<String> mText;

    public MeViewModel() {
        mText = new MutableLiveData<>();
        //  mText.setValue("This is me fragment");
    }

    public LiveData<String> getText() {
        return mText;
    }


    void up_down_bookrack(Handler handler, List<BookInfo> books, String url, boolean up) {
        String username = (String) Fun.SHARE_MAP.get(R.string.prompt_username);
        String password = (String) Fun.SHARE_MAP.get(R.string.prompt_password);
        if (null == username || null == password) {
            mText.setValue(ERROR + "：请登录");
            return;
        }

        final String encrypted = Fun.webEncrypted(username, password);
        Connection conn = Jsoup.connect(url);
        conn.data(ENCRYPTED, encrypted);
        conn.data(USER, username);
        conn.data(PASSWORD, password);
        if (up) {//上传
            int size = books.size();
            if (size > 0) {
                Tab_Book tabBook = new Tab_Book(content);
                conn.data("bookCount", String.valueOf(size));
                for (int i = 0; i < size; i++) {
                    BookInfo book = books.get(i);
                    Tab_BookProgress.BookProgress progress = tabBook.getTab_bookProgress().getProgress(book.getID());
                    int index = 0;
                    if (progress.chapterID != 0)
                        index = tabBook.getTab_chapter().getChapterIndex(book.getID(), progress.chapterID);
                    //书籍的本地索引，可以根据这个上传，下载的时候判断是否到这个索引，添加到数据库
                    conn.data("index" + i, String.valueOf(index));
                    conn.data("uri" + i, book.getFieldValue(R.string.info_uri));
                }
                new Thread(() -> {
                    try {
                        Document doc = conn.post();
                        handler.sendMessage(
                                handler.obtainMessage(HANDLER_TOAST,0,0,"上传" + doc.text()));
                    } catch (IOException e) {
                        handler.sendMessage(
                                handler.obtainMessage(HANDLER_TOAST,0,0,ERROR + content.getString(R.string.server_error)));
                    }
                }).start();
            }
        } else {//下载
            conn.data("bookCount", String.valueOf(-1));//-1服务器会判定为下载
            new Thread(() -> {
                Document doc = null;
                String str = "同步成功！重新打开软件可以刷新书籍封面";
                try {
                    doc = conn.post();
                } catch (IOException e) {
                    //e.printStackTrace();
                    str = ERROR + content.getString(R.string.server_error);
                }
                if (doc == null) {
                    str = ERROR + "无法获得服务器数据";
                } else {
                    Elements datas = doc.select("div");
                    int progress = 1;
                    if (datas.size() > 0) {
                        Tab_Book tab_book = new Tab_Book(content);
                        //  HashMap<Element,Boolean> checkedMap= new HashMap<>();
                        for (Element data : datas) {
                            String bookUri = data.child(0).text();
                            int index = Integer.parseInt(data.child(1).text());
                            boolean hasBook = false;
                            for (BookInfo book : books) {
                                if (bookUri.equals(book.getFieldValue(R.string.info_uri))) {
                                    //已经有书
                                    hasBook = true;
                                    long chapterID = tab_book.getTab_chapter().getChapterIdFromIndex(book.getID(), index);
                                    if (chapterID > 0)
                                        tab_book.getTab_bookProgress().update(book.getID(), chapterID);
                                    break;
                                }
                            }
                            //  checkedMap.put(data,hasBook);
                            if (!hasBook) {

                                BookInfo bookInfo = new BookInfo();
                                bookInfo.setFieldValue(R.string.info_uri, bookUri);
                                tab_book.add(bookInfo);

                                List<Map<String, String>> chapter_list = new ArrayList<>();
                                ChapterThread threadNoRun = new ChapterThread(bookInfo, chapter_list, null,
                                        true, true, content, bookInfo.getID(), true);
                                threadNoRun.getInfo();
                                tab_book.update(bookInfo);
                                long chapterID = tab_book.getTab_chapter().getChapterIdFromIndex(bookInfo.getID(), index);
                                if (chapterID > 0)
                                    tab_book.getTab_bookProgress().update(bookInfo.getID(), chapterID);
                                synchronized (books) {
                                    books.add(0,bookInfo);
                                }
                            }
                            Message msg = handler.obtainMessage(HANDLER_DOWN_BOOKRACK_PROGRESS);
                            msg.obj = "当前进度：" + progress++ + "/" + datas.size();
                            handler.sendMessage(msg);
                        }
                        tab_book.close();
                    } else
                        str = ERROR + "服务器没有数据";
                }
                Message msg = handler.obtainMessage(HANDLER_DOWN_BOOKRACK_FINISH);
                msg.obj=str;
                handler.sendMessage(msg);
            }).start();

        }
    }

    private Context content;

    public void setContent(Context content) {
        this.content = content;
    }

    void checkVersion(String versionUri, Handler handler) {
        new Thread(()->{
            Document doc;
            try {
                doc = Jsoup.connect(versionUri).timeout(5000).get();
            } catch (IOException e) {
                //e.printStackTrace();
                Message msg = handler.obtainMessage(HANDLER_CHECK_VERSION);
                msg .arg1 =-1;
                handler.sendMessage(msg);
                return;
            }
            if (doc!=null){
                PackageManager manager = content.getPackageManager();

                try {
                    PackageInfo info = manager.getPackageInfo(content.getPackageName(),0);
                    long version;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                         version = info.getLongVersionCode();
                    }else {
                         version = info.versionCode;
                    }
                    Message msg = handler.obtainMessage(HANDLER_CHECK_VERSION);
                    if (Long.parseLong(doc.text())>version){
                        msg .arg1 =1;
                    }else
                        msg.arg1  =0;
                    handler.sendMessage(msg);

                } catch (PackageManager.NameNotFoundException e) {
                    //e.printStackTrace();

                }
            }
        }).start();
    }
}